﻿@model UserListModel

@using System.Globalization;

@{
    var defaultGridPageSize = EngineContext.Current.Resolve<Giant.Core.Domain.Common.AdminAreaSettings>().DefaultGridPageSize;
    var gridPageSizes = EngineContext.Current.Resolve<Giant.Core.Domain.Common.AdminAreaSettings>().GridPageSizes;

    //page title
    ViewBag.Title = T("Admin.Users.Users").Text;
    //active menu item (system name)
    Html.SetActiveMenuItemSystemName("Users list");
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="content-header clearfix">
        <h1 class="pull-left">
            @T("Admin.Users.Users")
        </h1>
        <div class="pull-right">
            <a href="@Url.Action("Create")" class="btn bg-blue">
                <i class="fa fa-plus-square"></i>
                @T("Admin.Common.AddNew")
            </a>
            <div class="btn-group">
                <button type="button" class="btn btn-success">
                    <i class="fa fa-download"></i>
                    @T("Admin.Common.Export")
                </button>
                <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <span class="caret"></span>
                    <span class="sr-only">&nbsp;</span>
                </button>
                <ul class="dropdown-menu" role="menu">
                    <li>
                        <button type="submit" name="exportxml-all">
                            <i class="fa fa-file-code-o"></i>
                            @T("Admin.Common.ExportToXml.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="exportxml-selected">
                            <i class="fa fa-file-code-o"></i>
                            @T("Admin.Common.ExportToXml.Selected")
                        </button>
                    </li>
                    <li class="divider"></li>
                    <li>
                        <button type="submit" name="exportexcel-all">
                            <i class="fa fa-file-excel-o"></i>
                            @T("Admin.Common.ExportToExcel.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="exportexcel-selected">
                            <i class="fa fa-file-excel-o"></i>
                            @T("Admin.Common.ExportToExcel.Selected")
                        </button>
                    </li>
                </ul>
            </div>
        </div>
    </div>

    <div class="content">
        <div class="form-horizontal">
            <div class="panel-group">
                <div class="panel panel-default panel-search">
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-5">
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.ExtLabelFor(model => model.SearchEmail)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.ExtEditorFor(model => model.SearchEmail)
                                    </div>
                                </div>
                                @if (Model.UsernamesEnabled)
                                {
                                    <div class="form-group">
                                        <div class="col-md-4">
                                            @Html.ExtLabelFor(model => model.SearchUsername)
                                        </div>
                                        <div class="col-md-8">
                                            @Html.ExtEditorFor(model => model.SearchUsername)
                                        </div>
                                    </div>
                                }
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.ExtLabelFor(model => model.SearchFirstName)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.ExtEditorFor(model => model.SearchFirstName)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.ExtLabelFor(model => model.SearchLastName)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.ExtEditorFor(model => model.SearchLastName)
                                    </div>
                                </div>
                                @if (Model.DateOfBirthEnabled)
                                {
                                    <div class="form-group">
                                        <div class="col-md-4">
                                            @Html.ExtLabelFor(model => model.SearchDayOfBirth)
                                        </div>
                                        <div class="col-md-8">
                                            @{
                                                var monthOfBirthValues = new List<SelectListItem>();
                                                monthOfBirthValues.Add(new SelectListItem { Text = T("Admin.Users.Users.List.SearchDateOfBirth.Month").Text, Value = "0" });
                                                for (int i = 1; i <= 12; i++)
                                                {
                                                    monthOfBirthValues.Add(new SelectListItem { Text = i.ToString(CultureInfo.InvariantCulture), Value = i.ToString(CultureInfo.InvariantCulture) });
                                                }
                                                var dayOfBirthValues = new List<SelectListItem>();
                                                dayOfBirthValues.Add(new SelectListItem { Text = T("Admin.Users.Users.List.SearchDateOfBirth.Day").Text, Value = "0" });
                                                for (int i = 1; i <= 31; i++)
                                                {
                                                    dayOfBirthValues.Add(new SelectListItem { Text = i.ToString(CultureInfo.InvariantCulture), Value = i.ToString(CultureInfo.InvariantCulture) });
                                                }
                                            }
                                            <div class="row">
                                                <div class="col-md-6">
                                                    @Html.ExtDropDownListFor(model => model.SearchMonthOfBirth, monthOfBirthValues)
                                                </div>
                                                <div class="col-md-6">
                                                    @Html.ExtDropDownListFor(model => model.SearchDayOfBirth, dayOfBirthValues)
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                }
                            </div>
                            <div class="col-md-7">
                               
                                @if (Model.PhoneEnabled)
                                {
                                    <div class="form-group">
                                        <div class="col-md-4">
                                            @Html.ExtLabelFor(model => model.SearchPhone)
                                        </div>
                                        <div class="col-md-8">
                                            @Html.ExtEditorFor(model => model.SearchPhone)
                                        </div>
                                    </div>
                                }
                               
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.ExtLabelFor(model => model.SearchIpAddress)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.ExtEditorFor(model => model.SearchIpAddress)
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.ExtLabelFor(model => model.SearchUserRoleIds)
                                    </div>
                                    <div class="col-md-8">
                                        @Html.EditorFor(model => model.SearchUserRoleIds, new {SelectList = Model.AvailableUserRoles})
                                        <script>
                                            $(document).ready(function() {
                                                var rolesIdsInput = $('#@Html.FieldIdFor(model => model.SearchUserRoleIds)').data("kendoMultiSelect");
                                                rolesIdsInput.setOptions({
                                                    autoClose: false
                                                });

                                                @if (Model.AvailableUserRoles.Count == 0)
                                                {
                                                    <text>
                                                        rolesIdsInput.setOptions({
                                                            enable: false,
                                                            placeholder: '@T("Admin.Catalog.Products.UserRoles.NoUserRolesAvailable")'
                                                        });
                                                        rolesIdsInput._placeholder();
                                                        rolesIdsInput._enable();
                                                    </text>
                                                }
                                            });
                                        </script>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-7 col-md-offset-5">
                                <button type="button" id="search-users" class="btn btn-primary btn-search">
                                    <i class="fa fa-search"></i>
                                    @T("Admin.Common.Search")
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="panel panel-default">
                    <div class="panel-body">
                        <div id="users-grid"></div>

                        <script>
                            $(document).ready(function() {
                                $("#users-grid").kendoGrid({
                                    dataSource: {
                                        type: "json",
                                        transport: {
                                            read: {
                                                url: "@Html.Raw(Url.Action("UserList", "User"))",
                                                type: "POST",
                                                dataType: "json",
                                                data: additionalData
                                            }
                                        },
                                        schema: {
                                            data: "Data",
                                            total: "Total",
                                            errors: "Errors"
                                        },
                                        error: function(e) {
                                            display_kendoui_grid_error(e);
                                            // Cancel the changes
                                            this.cancelChanges();
                                        },
                                        pageSize: @(defaultGridPageSize),
                                        serverPaging: true,
                                        serverFiltering: true,
                                        serverSorting: true
                                    },
                                    pageable: {
                                        refresh: true,
                                        pageSizes: [@(gridPageSizes)]
                                    },
                                    scrollable: false,
                                    dataBound: onDataBound,
                                    columns: [
                                        {
                                            field: "Id",
                                            headerTemplate: "<input id='mastercheckbox' type='checkbox'/>",
                                            headerAttributes: { style: "text-align:center" },
                                            attributes: { style: "text-align:center" },
                                            template: "<input type='checkbox' value='#=Id#' class='checkboxGroups'/>",
                                            width: 50
                                        }, {
                                            field: "Id",
                                            title: "ID",
                                            width: 50
                                        }, {
                                            field: "Email",
                                            title: "@T("Admin.Users.Users.Fields.Email")",
                                            width: 200
                                        },
                                        @if (Model.UsernamesEnabled)
                                        {
                                            <text>{
                                            field: "Username",
                                            title: "@T("Admin.Users.Users.Fields.Username")",
                                            width: 200
                                        },</text>
                                        }
                                        {
                                            field: "FullName",
                                            title: "@T("Admin.Users.Users.Fields.FullName")",
                                            width: 200
                                        }, {
                                            field: "UserRoleNames",
                                            title: "@T("Admin.Users.Users.Fields.UserRoles")",
                                            width: 200
                                        },

                                        @if (Model.PhoneEnabled)
                                        {
                                            <text>{
                                            field: "Phone",
                                            title: "@T("Admin.Users.Users.Fields.Phone")",
                                            width: 200
                                        },</text>
                                        }                                       
                                        {
                                            field: "Active",
                                            title: "@T("Admin.Users.Users.Fields.Active")",
                                            width: 100,
                                            headerAttributes: { style: "text-align:center" },
                                            attributes: { style: "text-align:center" },
                                            template: '# if(Active) {# <i class="fa fa-check true-icon"></i> #} else {# <i class="fa fa-close false-icon"></i> #} #'
                                        }, {
                                            field: "CreatedOn",
                                            title: "@T("Admin.Users.Users.Fields.CreatedOn")",
                                            width: 200,
                                            type: "date",
                                            format: "{0:G}"
                                        }, {
                                            field: "LastActivityDate",
                                            title: "@T("Admin.Users.Users.Fields.LastActivityDate")",
                                            width: 200,
                                            type: "date",
                                            format: "{0:G}"
                                        }, {
                                            field: "Id",
                                            title: "@T("Admin.Common.Edit")",
                                            width: 50,
                                            template: '<a href="Edit/#=Id#">@T("Admin.Common.Edit")</a>'
                                        }
                                    ]
                                });
                            });
                        </script>

                        <script type="text/javascript">
                            var selectedIds = [];

                            $(document).ready(function() {
                                //search button
                                $('#search-users').click(function() {
                                    var grid = $('#users-grid').data('kendoGrid');
                                    grid.dataSource.page(1); //new search. Set page size to 1
                                    //grid.dataSource.read(); we already loaded the grid above using "page" function
                                    //clear selected checkboxes
                                    $('.checkboxGroups').attr('checked', false).change();
                                    selectedIds = [];
                                    return false;
                                });

                                $("".concat("#@Html.FieldIdFor(model => model.SearchEmail),",
                                    "#@Html.FieldIdFor(model => model.SearchUsername),",
                                    "#@Html.FieldIdFor(model => model.SearchFirstName),",
                                    "#@Html.FieldIdFor(model => model.SearchLastName),",
                                    "#@Html.FieldIdFor(model => model.SearchPhone),",
                                    "#@Html.FieldIdFor(model => model.SearchIpAddress)")).keydown(function(event) {
                                        if (event.keyCode === 13) {
                                            $("#search-users").click();
                                            return false;
                                        }
                                    });

                                $('#mastercheckbox').click(function() {
                                    $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
                                });

                                //wire up checkboxes.
                                $('#users-grid').on('change', 'input[type=checkbox][id!=mastercheckbox]', function(e) {
                                    var $check = $(this);
                                    if ($check.is(":checked") == true) {
                                        var checked = jQuery.inArray($check.val(), selectedIds);
                                        if (checked == -1) {
                                            //add id to selectedIds.
                                            selectedIds.push($check.val());
                                        }
                                    } else {
                                        var checked = jQuery.inArray($check.val(), selectedIds);
                                        if (checked > -1) {
                                            //remove id from selectedIds.
                                            selectedIds = $.grep(selectedIds, function(item, index) {
                                                return item != $check.val();
                                            });
                                        }
                                    }
                                    updateMasterCheckbox();
                                });
                            });

                            function onDataBound(e) {
                                $('#users-grid input[type=checkbox][id!=mastercheckbox]').each(function() {
                                    var currentId = $(this).val();
                                    var checked = jQuery.inArray(currentId, selectedIds);
                                    //set checked based on if current checkbox's value is in selectedIds.
                                    $(this).attr('checked', checked > -1);
                                });

                                updateMasterCheckbox();
                            }

                            function updateMasterCheckbox() {
                                var numChkBoxes = $('#users-grid input[type=checkbox][id!=mastercheckbox]').length;
                                var numChkBoxesChecked = $('#users-grid input[type=checkbox][id!=mastercheckbox]:checked').length;
                                $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
                            }

                            function additionalData() {
                                var data = {
                                    SearchUserRoleIds: $('#@Html.FieldIdFor(model => model.SearchUserRoleIds)').val(),
                                    SearchEmail: $('#@Html.FieldIdFor(model => model.SearchEmail)').val(),
                                    SearchUsername: $('#@Html.FieldIdFor(model => model.SearchUsername)').val(),
                                    SearchFirstName: $('#@Html.FieldIdFor(model => model.SearchFirstName)').val(),
                                    SearchLastName: $('#@Html.FieldIdFor(model => model.SearchLastName)').val(),
                                    SearchDayOfBirth: $('#@Html.FieldIdFor(model => model.SearchDayOfBirth)').val(),
                                    SearchMonthOfBirth: $('#@Html.FieldIdFor(model => model.SearchMonthOfBirth)').val(),
                                    SearchPhone: $('#@Html.FieldIdFor(model => model.SearchPhone)').val(),
                                    SearchIpAddress: $('#@Html.FieldIdFor(model => model.SearchIpAddress)').val()
                                };
                                addAntiForgeryToken(data);
                                return data;
                            }
                        </script>
                    </div>
                </div>
            </div>
        </div>
    </div>
                                                }

@*export selected (XML). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
@using (Html.BeginForm("ExportXmlSelected", "User", FormMethod.Post, new { id = "export-xml-selected-form" }))
{
    @Html.AntiForgeryToken()
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
}

<script type="text/javascript">
    $(document).ready(function () {
        $('#exportxml-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#export-xml-selected-form #selectedIds').val(ids);
            $('#export-xml-selected-form').submit();
            return false;
        });
    });
</script>

@*export selected (Excel). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
@using (Html.BeginForm("ExportExcelSelected", "User", FormMethod.Post, new { id = "export-excel-selected-form" }))
{
    @Html.AntiForgeryToken()
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
}
<script type="text/javascript">
    $(document).ready(function () {
        $('#exportexcel-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#export-excel-selected-form #selectedIds').val(ids);
            $('#export-excel-selected-form').submit();
            return false;
        });
    });
</script>
